<template>
  <div style="width: 100%">
    <el-collapse v-model="activeName">
      <el-collapse-item name="1" title="基本信息">
        <el-form ref="form" :disabled="disabled" size="small" :rules="rules" :model="formData"
                 label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="中文名称" prop="nameCn">
                <el-input v-model="formData.nameCn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关联条件" prop="conditionName">
                <el-select filterable style="width: 100%" v-model="formData.conditionName" @input="getEntity">
                  <template v-for="{name,nameCn} in condition">
                    <el-option :value="name" :label="nameCn"></el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="英文名称" prop="nameEn">
                <el-input v-model="formData.nameEn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实体类型">
                <el-input disabled v-model="entity"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="编码标识" prop="name">
                <el-input :disabled="dialogType!=='open'" v-model="formData.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="英文描述">
                <el-input v-model="formData.describeEn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="中文描述" prop="describeCn">
                <el-input v-model="formData.describeCn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="是否拒绝" prop="refuseFlag">
                <el-radio-group v-model="formData.refuseFlag">
                  <el-radio :label="1">拒绝</el-radio>
                  <el-radio :label="0">赋予</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="用户" prop="partyIds">
                <el-input type="textarea" resize="none" :rows="6"
                          v-model="formData.partyIds"></el-input>

                <div class="content" :class="dialogType==='view'?'view':''">
                  <template v-for="(item,index) in selectionPartyIds">
                    <el-tag :key="item.pid" :closable="dialogType!=='view'" size="small"
                            @close="closeTag(selectionPartyIds,index,'partyIds')">
                      {{ item.name ? item.name : item.firstName }}
                    </el-tag>
                  </template>
                </div>

                <el-button class="suffix"
                           type="primary"
                           size="small"
                           @click="selectInputVal()">
                  选择
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item name="2" title="操作列表">
        <avue-crud :option="option"
                   :table-loading="loading"
                   :data="data"
                   ref="crud">
          <template slot="selectionHeader" slot-scope="{column}">
            <el-checkbox :indeterminate="indeterminate"
                         :disabled="disabled"
                         v-model="checkAll"
                         @change="checkAllChange">
              {{ column.label }}
            </el-checkbox>
          </template>
          <template slot="selection" slot-scope="{row}">
            <el-checkbox v-model="row.checked" :disabled="disabled"></el-checkbox>
          </template>
        </avue-crud>
      </el-collapse-item>
      <el-collapse-item name="3" title="生效属性列表">
        <p>
          <el-button type="primary" size="small" :disabled="disabled" @click="selectAttribute">添加
          </el-button>
          <el-button size="small" :disabled="disabled"
                     @click="attributeIds=[],formData.attributeIds=''">
            清空
          </el-button>
        </p>
        <div class="ta">
          <el-input type="textarea" rows="5" resize="none" :disabled="disabled"></el-input>
          <div class="content" :class="dialogType==='view'?'view':''">
            <template v-for="(item,index) in attributeIds">
              <el-tag :key="item.oid" :closable="dialogType!=='view'" size="small"
                      @close="closeTag(attributeIds,index,'attributeIds')">
                {{ item.nameCn }}
              </el-tag>
            </template>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>

    <div class="md-component-btns">
      <el-button size="medium" type="primary" v-if="dialogType!=='view'" @click="save">确定</el-button>
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>

    <el-dialog :visible.sync="visible"
               title="选择用户集合"
               width="1000px"
               :modal-append-to-body="false">
      <div style="width: 100%;height: 500px" v-if="visible">
        <div class="tableGroup header_">
          <div>组织</div>
          <div>用户组</div>
          <div>角色</div>
          <div>用户</div>
        </div>
        <div class="tableGroup">
          <!--组织-->
          <avue-crud :option="setOption(users.option,'orgs')"
                     :data="users.data.orgs"
                     @selection-change="v=>$set(users.selection,'orgs',v)"
                     ref="orgs">
          </avue-crud>
          <!--用户组-->
          <avue-crud :option="setOption(users.option,'usergroups')"
                     :data="users.data.usergroups"
                     @selection-change="v=>$set(users.selection,'usergroups',v)"
                     ref="usergroups">
          </avue-crud>
          <!--角色-->
          <avue-crud :option="setOption(users.option,'roles')"
                     :data="users.data.roles"
                     @selection-change="v=>$set(users.selection,'roles',v)"
                     ref="roles">
          </avue-crud>
          <!--用户-->
          <avue-crud :option="setOption(users.option,'users')"
                     :data="users.data.users"
                     @selection-change="v=>$set(users.selection,'users',v)"
                     ref="users">
          </avue-crud>
        </div>
      </div>
      <div slot="footer">
        <el-button size="small" type="primary" @click="sure">确定</el-button>
        <el-button size="small" @click="visible=false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="visible_attribute"
               title="选择属性"
               width="1000px"
               :modal-append-to-body="false">
      <div style="width: 100%;height: 500px" v-if="visible_attribute">
        <avue-crud :option="attribute.option"
                   :data="attribute.data"
                   @selection-change="v=>$set(attribute,'selection',v)"
                   ref="attribute">
        </avue-crud>
      </div>

      <div slot="footer">
        <el-button size="medium" type="primary" @click="checkAttribute">确定</el-button>
        <el-button size="medium" @click="visible_attribute=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as api from "@/api/menu";
import {
  operateGroupList,
  conditionList,
  attributeList,
  save,
  detail,
  update,
  unCheckOut,
  checkout
} from "@/api/tactics/tactics";

export default {
  name: "tacticsTemp",
  data() {
    return {
      activeName: ["1", "2", "3"],
      formData: {
        nameCn: "",
        name: "",
        nameEn: "",
        describeCn: "",
        describeEn: "",
        refuseFlag: 0,
        conditionName: "",
        partyIds: "",
        operationGroupIds: "",
        attributeIds: ""
      },
      rules: {
        name: [{
          required: true,
          trigger: 'blur',
          message: "请输入编码标识"
        }, {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确编码标识'}],
        nameCn: [{required: true, trigger: 'blur', message: "请输入中文名称"}],
        nameEn: [{required: true, trigger: 'blur', message: "请输入英文名称"}],
        describeCn: [{required: true, trigger: 'blur', message: "请输入中文描述"}],
        refuseFlag: [{required: true, trigger: 'change', message: "请选择是否拒绝"}],
        conditionName: [{required: true, trigger: 'change', message: "请选择关联条件"}],
        partyIds: [{required: true, trigger: 'change', message: "请选择用户"}],
      },

      data: [],
      loading: false,
      option: {
        height: '300',
        calcHeight: 0,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        selection: false,
        labelWidth: 120,
        menuWidth: 200,
        viewBtn: false,
        dialogClickModal: false,
        tabs: true,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        align: "left",
        menu: false,
        header: false,
        column: [
          {
            label: "中文名称",
            prop: "name",
            msSearch: true,
            searchOrder: 4
          },
          {
            label: '英文名称',
            prop: 'templateType',
            msSearch: true,
            searchOrder: 0
          },
          {
            label: "中文描述",
            prop: "serviceName",
          },
          {
            label: "英文描述",
            prop: "packageName",
          },
          {
            label: '是否选中',
            prop: 'selection',
            width: "120",
            formSlot: "selection"
          },
        ]
      },
      checkAll: false,

      dialogType: "open",

      condition: [],

      visible: false,
      users: {
        keys: [
          {key: "usergroups", label: "用户组"},
          {key: "roles", label: "角色"},
          {key: "orgs", label: "组织"},
          {key: "users", label: "用户"}
        ],
        // usergroups   roles   orgs    users
        data: {},
        selection: {usergroups: [], roles: [], orgs: [], users: []},
        option: {
          height: '450',
          calcHeight: 10,
          dialogWidth: 900,
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          labelWidth: 120,
          menuWidth: 200,
          viewBtn: false,
          dialogClickModal: false,
          tabs: true,
          delBtn: false,
          addBtn: false,
          editBtn: false,
          refreshBtn: false,
          columnBtn: false,
          align: "center",
          menu: false,
          rowKey: 'oid',
          rowParentKey: 'parentId',
          tree: true,
          lazy: true,
          header: false,
          selection: true,
          column: [],
          usergroups: [
            {label: "用户组名称", prop: "name",},
          ],
          roles: [
            {label: "角色名称", prop: "name",},
          ],
          users: [
            {label: "用户名称", prop: "username",},
          ],
          orgs: [
            {label: "组织名称", prop: "name",},
          ],
        },
      },
      selectionPartyIds: [],
      recirculationSelection: [],

      entity: "",

      visible_attribute: false,
      attributeIds: [],
      attribute: {
        data: [],
        selection: [],
        option: {
          height: '450',
          calcHeight: 10,
          dialogWidth: 900,
          tip: false,
          searchShow: false,
          searchMenuSpan: 6,
          border: true,
          index: false,
          labelWidth: 120,
          menuWidth: 200,
          viewBtn: false,
          dialogClickModal: false,
          tabs: true,
          delBtn: false,
          addBtn: false,
          editBtn: false,
          refreshBtn: false,
          columnBtn: false,
          align: "left",
          menu: false,
          rowKey: 'oid',
          rowParentKey: 'parentId',
          tree: true,
          lazy: true,
          header: false,
          selection: true,
          column: [
            {label: "属性", prop: "nameCn"},
            {
              label: "是否动态属性",
              prop: "dynamicFlag",
              align: "center",
              dicData: [{label: "是", value: 1}, {label: "否", value: 0}]
            },
          ]
        }
      }
    }
  },
  computed: {
    disabled() {
      return this.dialogType === "view";
    },
    indeterminate() {
      this.checkAll = false;

      let checkNum = 0;
      this.data.forEach(i => {
        checkNum += i.checked ? 1 : 0;
      })

      if (checkNum === this.data.length) {
        this.checkAll = true;
        return false;
      }

      if (checkNum === 0) {
        return false;
      }

      return checkNum !== this.data.length;
    }
  },
  methods: {
    setOption(option, objName) {
      let opt = this.deepCopy(option);
      opt.column = option[objName]
      return opt
    },

    save() {
      this.$refs["form"].validate(f => {
        if (f) {
          if (this.attributeIds.length === this.attribute.data.length) {
            this.formData.attributeIds = 1;
          } else {
            this.formData.attributeIds = this.deepCopy(this.attributeIds).map(item => item["oid"]).join(",")
          }

          let d = [];
          this.data.forEach(i => {
            if (i.checked) {
              d.push(i)
            }
          })
          this.formData.operationGroupIds = d.map(i => i.oid).join(",");

          if (this.dialogType === "edit") {
            update(this.formData).then(() => {
              this.$emit('removeThisTabs');
              this.$message.success("保存成功");
              this.$emit("refresh");
            })
          } else {
            save(this.formData).then(() => {
              this.$emit('removeThisTabs');
              this.$message.success("保存成功");
              this.$emit("refresh");
            })
          }
        }
      })
    },

    selectAttribute() {
      this.visible_attribute = true;

      this.$nextTick(() => {
        let ids = this.attributeIds.map(i => i.oid).join(",");
        this.attribute.data.forEach(item => {
          if (ids.includes(item.oid)) {
            this.$refs["attribute"].toggleRowSelection(item, true);
          }
        })
      })
    },
    checkAttribute() {
      this.visible_attribute = false
      this.attributeIds = this.deepCopy(this.attribute.selection);
      this.formData.attributeIds = this.deepCopy(this.attribute.selection).map(item => item["oid"]).join(",")
    },

    checkAllChange(checked) {
      this.indeterminate = !checked;
      this.checkAll = checked;

      this.data.forEach(i => {
        i.checked = checked;
      })

      let d = this.data;
      this.formData.operationGroupIds = d.map(i => i.oid).join(",");
    },

    open() {
      this.dialogType = "open";
      this.requestBeforeOpen();
    },
    async view(row) {
      this.getUsers();
      await this.getConditionList();
      this.dialogType = "view";
      detail({id: row.oid}).then(res => {
        this.getDetails(res);
      })

    },
    async edit(row) {
      this.getUsers();
      await this.getConditionList();
      this.dialogType = "edit";
      checkout({id: row.oid}).then(res => {
        this.getDetails(res);
        this.$emit("refresh");
      })
    },

    getDetails(res) {
      let d = res.data.data;
      Object.assign(this.formData, d)
      this.attributeIds = this.deepCopy(d.attributeList);
      this.selectionPartyIds = this.deepCopy(d.partyList);
      this.formData.partyIds = this.formData.partyList.map(i => i.oid).join(",");

      this.getEntity(this.formData.conditionName);
    },

    requestBeforeOpen() {
      this.getUsers();
      this.getConditionList();
    },

    getEntity(v) {
      let d = this.condition.filter(i => i.name === v);
      this.entity = d[0].typeNameCn;

      operateGroupList({conditionName: v}).then(res => {
        let ids = [];
        if (this.formData.operationGroupList && this.formData.operationGroupList.length > 0) {
          ids = this.formData.operationGroupList.map(i => i.oid);
        }
        res.data.data.forEach(i => {
          i.checked = ids.includes(i.oid);
        })
        this.data = res.data.data;
      })

      attributeList({typeName: d[0].typeName}).then(res => {
        this.attribute.data = res.data.data;
      })
    },

    async getConditionList() {
      await conditionList({enableState: 1}).then(res => {
        this.condition = res.data.data;
      })
    },

    getUsers() {
      /*
      * usergroups  用户组
      * roles       角色
      * orgs        组织
      * users       用户列表
      * */
      api.getUserCollect().then(res => {
        this.users.data = res.data.data;
      })
    },
    closeTag(data, index, model) {
      data.splice(index, 1);
      this.formData[model] = this.deepCopy(data).map(item => item["oid"]).join(",");
    },
    sure() {
      this.visible = false;
      this.selectionPartyIds = [];
      let users = this.users.selection
      for (const key in users) {
        if (users[key] && users[key].length > 0) {
          this.selectionPartyIds.push(...users[key]);
        }
      }
      this.formData.partyIds = this.deepCopy(this.selectionPartyIds).map(item => item.pid).join(",");
      this.users.selection = {usergroups: [], roles: [], orgs: [], users: []};
    },
    selectInputVal() {
      this.visible = true;
      this.recirculationSelection = this.selectionPartyIds;

      this.$nextTick(() => {
        this.toggleRowSelection();
      })
    },
    toggleRowSelection() {
      this.users.selection = {usergroups: [], roles: [], orgs: [], users: []};
      if (this.recirculationSelection && this.recirculationSelection.length > 0) {
        let ids = this.recirculationSelection.map(item => item.oid ? item.oid : item.pid);
        // 说明此列表不存在 oid
        // 整行数据转为 String 进行对比匹配
        for (const key in this.users.data) {
          this.users.data[key].forEach(item => {
            if (ids.includes(item.pid)) {
              this.$refs[key].toggleRowSelection(item, true);
            }
          })
        }
      }
    },
  }
}
</script>
<style scoped lang="scss">
.el-collapse {
  .el-collapse-item {
    .el-collapse-item__wrap {
      .el-collapse-item__content {
        .el-form {
          .el-row {
            .el-col {
              .el-form-item {
                .el-form-item__content {
                  position: relative;

                  .content {
                    position: absolute;
                    z-index: 99;
                    top: 5px;
                    left: 15px;
                    width: calc(100% - 30px);
                    height: calc(100% - 10px);
                    background: white;
                    overflow-y: scroll;

                    .el-tag {
                      margin-right: 5px;
                      margin-bottom: 5px;
                    }

                    > div {
                      line-height: 1;
                      font-size: 12px;
                      font-weight: normal;
                    }
                  }

                  .view {
                    background: #F5F7FA;
                  }

                  .suffix {
                    position: absolute;
                    right: 10px;
                    bottom: 10px;
                    z-index: 100;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

.ta {
  position: relative;

  .content {
    position: absolute;
    z-index: 99;
    top: 5px;
    left: 15px;
    width: calc(100% - 30px);
    height: calc(100% - 10px);
    background: white;
    overflow-y: scroll;

    .el-tag {
      margin-right: 5px;
      margin-bottom: 5px;
    }

    > div {
      line-height: 1;
      font-size: 12px;
      font-weight: normal;
    }
  }

  .view {
    background: #F5F7FA;
  }

  .suffix {
    position: absolute;
    right: 10px;
    bottom: 10px;
    z-index: 100;
  }
}

.tableGroup {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: nowrap;

  .avue-crud {
    width: 24%;
  }
}

.header_ {
  > div {
    width: 25%;
    text-indent: 10px;
    padding-bottom: 5px;
    font-size: 14px;
    font-weight: bold;
  }
}
</style>
